package com.longxi.tianjintianbao.ui.presenter.equipment;

import android.content.Intent;
import android.net.Uri;
import android.provider.Settings;
import android.widget.Toast;

import com.longxi.tianjintianbao.AppConst;
import com.longxi.tianjintianbao.MyApplication;
import com.longxi.tianjintianbao.R;
import com.longxi.tianjintianbao.api.ApiRetrofit;
import com.longxi.tianjintianbao.api.response.HttpResult;
import com.longxi.tianjintianbao.exception.ExceptionHandle;
import com.longxi.tianjintianbao.exception.MySubscriber;
import com.longxi.tianjintianbao.model.equipment.Equipment;
import com.longxi.tianjintianbao.ui.activity.equipment.EquipmentDetailsActivity;
import com.longxi.tianjintianbao.ui.activity.scan.ScanActivity;
import com.longxi.tianjintianbao.ui.adapter.multitype.equipment.EquipmentViewBinder;
import com.longxi.tianjintianbao.ui.base.BaseActivity;
import com.longxi.tianjintianbao.ui.base.BasePresenter;
import com.longxi.tianjintianbao.ui.view.equipment.IEquipmentAtView;
import com.longxi.tianjintianbao.utils.MyUtils;
import com.longxi.tianjintianbao.utils.NListRefresh;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

import me.drakeet.multitype.Items;
import me.drakeet.multitype.MultiTypeAdapter;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class EquipmentAtPresenter extends BasePresenter<IEquipmentAtView> {

    private MultiTypeAdapter adapter;
    private Items items;
    public int page = 0;

    public EquipmentAtPresenter(BaseActivity context) {
        super(context);
    }

    public void initAdapter(){
        if(adapter == null){
            adapter = new MultiTypeAdapter();
            /* 注册类型和 View 的对应关系 */
            adapter.register(Equipment.class, new EquipmentViewBinder(new EquipmentViewBinder.SelectEquipmentListener() {
                @Override
                public void onSuccess(int position) {
                    Equipment equipment = (Equipment) items.get(position);
                    Intent intent = new Intent(mContext, EquipmentDetailsActivity.class);
                    intent.putExtra(AppConst.ASSETID, equipment.getAssetid());
                    mContext.startActivity(intent);
                }
            }));
            getView().getRvContent().setAdapter(adapter);
        }
    }

    public void setBar() {
        mContext.setTitle(mContext.getIntent().getStringExtra(AppConst.TITLE));
        mContext.setTvLeft(MyUtils.getString(R.string.home));
//        mContext.setIvRight(R.mipmap.ic_scan);
    }

    /**
     * 测试数据
     */
    public void getEquipmentType(){
        JSONObject object = new JSONObject();
        try {
            object.put("userid", MyApplication.loginUser.userid);
            object.put("type", mContext.getIntent().getStringExtra(AppConst.TYPE));
            object.put("page", page);
            object.put("rowcount", "10");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        ApiRetrofit.getInstance().getAssetsList(object)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new MySubscriber<HttpResult<Equipment>>(mContext) {
            @Override
            public void onError(ExceptionHandle.ResponeThrowable throwable) {
                MyUtils.showToast(throwable.message);
                mContext.showError();
            }

            @Override
            public void onNext(HttpResult<Equipment> result) {
                items = NListRefresh.getInstance().fjData(result,
                        getView().getRefreshLayout(),
                        items,
                        adapter,
                        mContext);
            }
        });
    }

    public void scan() {
        AndPermission.with(mContext)
        .permission(Permission.CAMERA, Permission.READ_EXTERNAL_STORAGE)
        .onGranted(new Action() {
            @Override
            public void onAction(List<String> permissions) {
                Intent intent = new Intent(mContext, ScanActivity.class);
                mContext.startActivityForResult(intent, AppConst.IntentRequstCode.REQUEST_CODE_SCAN);
            }
        })
        .onDenied(new Action() {
            @Override
            public void onAction(List<String> permissions) {
                Uri packageURI = Uri.parse("package:" + mContext.getPackageName());
                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                mContext.startActivity(intent);

                Toast.makeText(mContext, "没有权限无法扫描呦", Toast.LENGTH_LONG).show();
            }
        }).start();
    }

    public void onActivityResult(int requestCode, Intent data) {
        switch (requestCode) {
            case AppConst.IntentRequstCode.REQUEST_CODE_SCAN:
//                if (data != null) {
//                    if (null != data) {
//                        Bundle bundle = data.getExtras();
//                        if (bundle == null) {
//                            return;
//                        }
//                        if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
//                            String result = bundle.getString(CodeUtils.RESULT_STRING);
//                            String key = "SB_";
//                            if(!result.contains(key)){
//                                MyUtils.showToast("该二维码不是设备二维码");
//                                return;
//                            }
//
//                            result = result.replace(key, "");
//
//                            try {
//                                LogUtils.d("二维码结果", result);
//                                int a = Integer.parseInt(result);
//                                Intent intent = new Intent(mContext, EquipmentDetailsActivity.class);
//                                intent.putExtra(EquipmentDetailsAtPresenter.EQUIPMENTID, result);
//                                mContext.startActivity(intent);
//                            } catch (NumberFormatException e) {
//                                e.printStackTrace();
//                                MyUtils.showToast("该二维码不是巡检二维码");
//                            }
//                        } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
//                            MyUtils.showToast("解析二维码失败");
//                        }
//                    }
//                }
                break;
        }
    }

    @Override
    public void detachView() {
        super.detachView();
        this.adapter = null;
        this.items = null;
    }
}
